<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="技术博客,php,java,python,go" />


<meta name="description" content="使用插件扩展功能appInit 标签中绑定InitHooks插件代码如下，见application\tags.php 123456789&amp;lt;?php// 应用行为扩展定义文件return [    // 应用初始化    &apos;app_init&apos;     =&amp;gt; [&apos;app\common\behavior\InitHooks&apos;],     .     .     .];">
<meta property="og:type" content="article">
<meta property="og:title" content="jshop thinkphp开源电商系统笔记">
<meta property="og:url" content="http://blog.yunshu168.com/posts/d2691605.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="使用插件扩展功能appInit 标签中绑定InitHooks插件代码如下，见application\tags.php 123456789&amp;lt;?php// 应用行为扩展定义文件return [    // 应用初始化    &apos;app_init&apos;     =&amp;gt; [&apos;app\common\behavior\InitHooks&apos;],     .     .     .];">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-03-12T06:08:18.164Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="jshop thinkphp开源电商系统笔记">
<meta name="twitter:description" content="使用插件扩展功能appInit 标签中绑定InitHooks插件代码如下，见application\tags.php 123456789&amp;lt;?php// 应用行为扩展定义文件return [    // 应用初始化    &apos;app_init&apos;     =&amp;gt; [&apos;app\common\behavior\InitHooks&apos;],     .     .     .];">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/d2691605.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>jshop thinkphp开源电商系统笔记 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/d2691605.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">jshop thinkphp开源电商系统笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-12T09:59:59+08:00">2019-09-12</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="使用插件扩展功能"><a href="#使用插件扩展功能" class="headerlink" title="使用插件扩展功能"></a>使用插件扩展功能</h3><h4 id="appInit-标签中绑定InitHooks插件"><a href="#appInit-标签中绑定InitHooks插件" class="headerlink" title="appInit 标签中绑定InitHooks插件"></a>appInit 标签中绑定InitHooks插件</h4><p>代码如下，见<code>application\tags.php</code></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="comment">// 应用行为扩展定义文件</span></span><br><span class="line"><span class="keyword">return</span> [</span><br><span class="line">    <span class="comment">// 应用初始化</span></span><br><span class="line">    <span class="string">'app_init'</span>     =&gt; [<span class="string">'app\common\behavior\InitHooks'</span>],</span><br><span class="line">     .</span><br><span class="line">     .</span><br><span class="line">     .</span><br><span class="line">];</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>初始化钩子类做的工作主要是从数据库表中取出插件，然后导入插件，它的代码如下：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">behavior</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">think</span>\<span class="title">facade</span>\<span class="title">Cache</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">think</span>\<span class="title">facade</span>\<span class="title">Hook</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">Hooks</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">Addons</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InitHooks</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 初始化钩子</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $params</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">run</span><span class="params">($params)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">//if(isset($_GET['m']) &amp;&amp; $_GET['m'] === 'Install') return; //屏蔽安装程序</span></span><br><span class="line">        $data = Cache::get(<span class="string">'hooks'</span>);</span><br><span class="line">        $hooksModel  = <span class="keyword">new</span> Hooks();</span><br><span class="line">        $addonsModel = <span class="keyword">new</span> Addons();</span><br><span class="line">        <span class="keyword">if</span> (!$data) &#123;</span><br><span class="line">            $hooks = $hooksModel-&gt;field(<span class="string">'name,addons'</span>)-&gt;select();</span><br><span class="line">            <span class="keyword">if</span> (!$hooks-&gt;isEmpty()) &#123;</span><br><span class="line">                $hooks = $hooks-&gt;toArray();</span><br><span class="line">                <span class="keyword">foreach</span> ($hooks <span class="keyword">as</span> $key =&gt; $value) &#123;</span><br><span class="line">                    <span class="keyword">if</span> ($value) &#123;</span><br><span class="line">                        $where = [];</span><br><span class="line">                        <span class="comment">//取出可用插件，然后把可用插件加入钩子</span></span><br><span class="line">                        $where[] = [<span class="string">'status'</span>, <span class="string">'eq'</span>, $addonsModel::INSTALL_STATUS];</span><br><span class="line">                        $names   = explode(<span class="string">','</span>, $value[<span class="string">'addons'</span>]);</span><br><span class="line">                        $where[] = [<span class="string">'name'</span>, <span class="string">'in'</span>, $names];</span><br><span class="line">                        $data    = $addonsModel-&gt;where($where)-&gt;field(<span class="string">'name'</span>)-&gt;select();</span><br><span class="line">                        <span class="keyword">if</span> (!$data-&gt;isEmpty()) &#123;</span><br><span class="line">                            $data        = $data-&gt;toArray();</span><br><span class="line">                            $data        = array_column($data, <span class="string">'name'</span>);</span><br><span class="line">                            $addons      = array_intersect($names, $data);    <span class="comment">// 查出在hooks表定义的插件列表</span></span><br><span class="line">                            $addons_list = array_filter(array_map(<span class="string">'get_addon_class'</span>, $addons));</span><br><span class="line">                            Hook::add($value[<span class="string">'name'</span>], $addons_list);   <span class="comment">//  将钩子添加到 Hooks类的tags 钩子属性数组中</span></span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                Cache::set(<span class="string">'hooks'</span>, Hook::get());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"></span><br><span class="line">            Hook::import($data, <span class="keyword">false</span>);   <span class="comment">// 合并$data和Hook-&gt;tags，重新赋值给Hook-&gt;tags</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>插件表定义：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`jshop_addons`</span> (</span><br><span class="line">  <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">10</span>) <span class="keyword">unsigned</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT <span class="keyword">COMMENT</span> <span class="string">'主键'</span>,</span><br><span class="line">  <span class="string">`name`</span> <span class="built_in">varchar</span>(<span class="number">40</span>) <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> utf8 <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'插件名或标识'</span>,</span><br><span class="line">  <span class="string">`title`</span> <span class="built_in">varchar</span>(<span class="number">20</span>) <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> utf8 <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">''</span> <span class="keyword">COMMENT</span> <span class="string">'中文名'</span>,</span><br><span class="line">  <span class="string">`description`</span> <span class="built_in">text</span> <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> utf8 <span class="keyword">COMMENT</span> <span class="string">'插件描述'</span>,</span><br><span class="line">  <span class="string">`status`</span> tinyint(<span class="number">1</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">'1'</span> <span class="keyword">COMMENT</span> <span class="string">'状态'</span>,</span><br><span class="line">  <span class="string">`config`</span> <span class="built_in">text</span> <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> utf8 <span class="keyword">COMMENT</span> <span class="string">'配置'</span>,</span><br><span class="line">  <span class="string">`author`</span> <span class="built_in">varchar</span>(<span class="number">40</span>) <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> utf8 <span class="keyword">DEFAULT</span> <span class="string">''</span> <span class="keyword">COMMENT</span> <span class="string">'作者'</span>,</span><br><span class="line">  <span class="string">`version`</span> <span class="built_in">varchar</span>(<span class="number">20</span>) <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> utf8 <span class="keyword">DEFAULT</span> <span class="string">''</span> <span class="keyword">COMMENT</span> <span class="string">'版本号'</span>,</span><br><span class="line">  <span class="string">`ctime`</span> <span class="built_in">int</span>(<span class="number">10</span>) <span class="keyword">unsigned</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">'0'</span> <span class="keyword">COMMENT</span> <span class="string">'安装时间'</span>,</span><br><span class="line">  <span class="string">`utime`</span> <span class="built_in">int</span>(<span class="number">10</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">'0'</span> <span class="keyword">COMMENT</span> <span class="string">'更新时间'</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>) <span class="keyword">USING</span> BTREE</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">10</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8mb4 <span class="keyword">COMMENT</span>=<span class="string">'插件表'</span></span><br></pre></td></tr></table></figure>
<p>钩子表定义：<br><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`jshop_hooks`</span> (</span><br><span class="line">  <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">10</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  <span class="string">`name`</span> <span class="built_in">varchar</span>(<span class="number">50</span>) <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> utf8 <span class="keyword">DEFAULT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'钩子名称'</span>,</span><br><span class="line">  <span class="string">`description`</span> <span class="built_in">text</span> <span class="keyword">COMMENT</span> <span class="string">'钩子描述'</span>,</span><br><span class="line">  <span class="string">`type`</span> tinyint(<span class="number">1</span>) <span class="keyword">DEFAULT</span> <span class="string">'1'</span> <span class="keyword">COMMENT</span> <span class="string">'钩子类型,1是控制器，2是视图'</span>,</span><br><span class="line">  <span class="string">`addons`</span> <span class="built_in">text</span> <span class="keyword">COMMENT</span> <span class="string">'钩子挂载的插件，逗号分隔'</span>,</span><br><span class="line">  <span class="string">`ctime`</span> <span class="built_in">int</span>(<span class="number">10</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'创建时间'</span>,</span><br><span class="line">  <span class="string">`utime`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">DEFAULT</span> <span class="string">'0'</span> <span class="keyword">COMMENT</span> <span class="string">'更新时间'</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>) <span class="keyword">USING</span> BTREE</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">10013</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8mb4</span><br></pre></td></tr></table></figure></p>
<h4 id="定义应用功能插件"><a href="#定义应用功能插件" class="headerlink" title="定义应用功能插件"></a>定义应用功能插件</h4><p>实现插件基类</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">myxland</span>\<span class="title">addons</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">think</span>\<span class="title">Db</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">think</span>\<span class="title">Controller</span>;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 插件基类</span></span><br><span class="line"><span class="comment"> * Class Addons</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@package</span> myxland\addons</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Addons</span> <span class="keyword">extends</span> <span class="title">Controller</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 当前错误信息</span></span><br><span class="line">    <span class="keyword">protected</span> $error;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * $info = [</span></span><br><span class="line"><span class="comment">     *  'name'          =&gt; 'Test',</span></span><br><span class="line"><span class="comment">     *  'title'         =&gt; '测试插件',</span></span><br><span class="line"><span class="comment">     *  'description'   =&gt; '用于thinkphp5的插件扩展演示',</span></span><br><span class="line"><span class="comment">     *  'status'        =&gt; 1,</span></span><br><span class="line"><span class="comment">     *  'author'        =&gt; 'byron sampson',</span></span><br><span class="line"><span class="comment">     *  'version'       =&gt; '0.1'</span></span><br><span class="line"><span class="comment">     * ]</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> $info = [];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> $addons_path = <span class="string">''</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> $config_file = <span class="string">''</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 架构函数</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@access</span> public</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// 获取当前插件目录</span></span><br><span class="line">        <span class="keyword">$this</span>-&gt;addons_path = ADDON_PATH . <span class="keyword">$this</span>-&gt;getName() . DIRECTORY_SEPARATOR;</span><br><span class="line">        <span class="comment">// 读取当前插件配置信息</span></span><br><span class="line">        <span class="keyword">if</span> (is_file(<span class="keyword">$this</span>-&gt;addons_path . <span class="string">'config.php'</span>)) &#123;</span><br><span class="line">            <span class="keyword">$this</span>-&gt;config_file = <span class="keyword">$this</span>-&gt;addons_path . <span class="string">'config.php'</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 控制器初始化</span></span><br><span class="line">        <span class="keyword">parent</span>::__construct();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取插件的配置数组</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> string $name 可选模块名</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> array|mixed|null</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getConfig</span><span class="params">($name = <span class="string">''</span>)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">static</span> $_config = [];</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">empty</span>($name)) &#123;</span><br><span class="line">            $name = <span class="keyword">$this</span>-&gt;getName();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">isset</span>($_config[$name])) &#123;</span><br><span class="line">            <span class="keyword">return</span> $_config[$name];</span><br><span class="line">        &#125;</span><br><span class="line">        $map[<span class="string">'name'</span>]   = $name;</span><br><span class="line">        $map[<span class="string">'status'</span>] = <span class="number">1</span>;</span><br><span class="line">        $config        = [];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (is_file(<span class="keyword">$this</span>-&gt;config_file)) &#123;</span><br><span class="line">            $temp_arr = <span class="keyword">include</span> <span class="keyword">$this</span>-&gt;config_file;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">foreach</span> ($temp_arr <span class="keyword">as</span> $key =&gt; $value) &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">isset</span>($value[<span class="string">'type'</span>]) &amp;&amp; $value[<span class="string">'type'</span>] == <span class="string">'group'</span>) &#123;</span><br><span class="line">                    <span class="keyword">foreach</span> ($value[<span class="string">'options'</span>] <span class="keyword">as</span> $gkey =&gt; $gvalue) &#123;</span><br><span class="line">                        <span class="keyword">foreach</span> ($gvalue[<span class="string">'options'</span>] <span class="keyword">as</span> $ikey =&gt; $ivalue) &#123;</span><br><span class="line">                            $config[$ikey] = $ivalue[<span class="string">'value'</span>];</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    $config[$key] = $temp_arr[$key][<span class="string">'value'</span>];</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">unset</span>($temp_arr);</span><br><span class="line">        &#125;</span><br><span class="line">        $_config[$name] = $config;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $config;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取当前模块名</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> string</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getName</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $data = explode(<span class="string">'\\'</span>, get_class(<span class="keyword">$this</span>));</span><br><span class="line">        $class_name = array_pop($data);</span><br><span class="line">        <span class="keyword">return</span> array_pop($data);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 检查配置信息是否完整</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> bool</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">checkInfo</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $info_check_keys = [<span class="string">'name'</span>, <span class="string">'title'</span>, <span class="string">'description'</span>, <span class="string">'status'</span>, <span class="string">'author'</span>, <span class="string">'version'</span>];</span><br><span class="line">        <span class="keyword">foreach</span> ($info_check_keys <span class="keyword">as</span> $value) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!array_key_exists($value, <span class="keyword">$this</span>-&gt;info)) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 加载模板和页面输出 可以返回输出内容</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@access</span> public</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> string $template 模板文件名或者内容</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> array $vars 模板输出变量</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> array $replace 替换内容</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> array $config 模板参数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> mixed</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> \Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="function"><span class="keyword">function</span> <span class="title">fetch</span><span class="params">($template = <span class="string">''</span>, $vars = [], $replace = [], $config = [])</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!is_file($template)) &#123;</span><br><span class="line">            $template = <span class="string">'/'</span> . $template;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 关闭模板布局</span></span><br><span class="line">        <span class="keyword">$this</span>-&gt;view-&gt;engine-&gt;layout(<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">$this</span>-&gt;view-&gt;engine([<span class="string">'view_path'</span>=&gt;  <span class="keyword">$this</span>-&gt;addons_path]);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">parent</span>::fetch($template, $vars, $replace, $config);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 模板变量赋值</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@access</span> protected</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> mixed $name 要显示的模板变量</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> mixed $value 变量的值</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="function"><span class="keyword">function</span> <span class="title">assign</span><span class="params">($name, $value = <span class="string">''</span>)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">       <span class="keyword">return</span> <span class="keyword">parent</span>::assign($name, $value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取当前错误信息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> mixed</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getError</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;error;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//必须实现安装</span></span><br><span class="line">    <span class="keyword">abstract</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">install</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//必须卸载插件方法</span></span><br><span class="line">    <span class="keyword">abstract</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">uninstall</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//必须实现配置函数</span></span><br><span class="line">    <span class="keyword">abstract</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">config</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取弹窗配置</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getDialog</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $info = <span class="keyword">$this</span>-&gt;info;</span><br><span class="line">        $dialog[<span class="string">'width'</span>] = $info[<span class="string">'dialog_width'</span>]?$info[<span class="string">'dialog_width'</span>]:<span class="string">'600px'</span>;</span><br><span class="line">        $dialog[<span class="string">'height'</span>] = $info[<span class="string">'dialog_height'</span>]?$info[<span class="string">'dialog_height'</span>]:<span class="string">'520px'</span>;</span><br><span class="line">        <span class="keyword">return</span> $dialog;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 显示错误信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $msg</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">showError</span><span class="params">($msg)</span></span>&#123;</span><br><span class="line">        header(<span class="string">"Content-type: text/html; charset=utf-8"</span>);</span><br><span class="line">        <span class="keyword">echo</span> $msg;<span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>插件类，如发送短信插件 <code>Aliyunsms</code>：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="comment">// +----------------------------------------------------------------------</span></span><br><span class="line"><span class="comment">// | JSHOP [ 小程序商城 ]</span></span><br><span class="line"><span class="comment">// +----------------------------------------------------------------------</span></span><br><span class="line"><span class="comment">// | Copyright (c) 2018 http://jihainet.com All rights reserved.</span></span><br><span class="line"><span class="comment">// +----------------------------------------------------------------------</span></span><br><span class="line"><span class="comment">// | Author: mark &lt;jima@jihainet.com&gt;</span></span><br><span class="line"><span class="comment">// +----------------------------------------------------------------------</span></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">addons</span>\<span class="title">Aliyunsms</span>;    <span class="comment">// 注意命名空间规范</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">myxland</span>\<span class="title">addons</span>\<span class="title">Addons</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">Addons</span> <span class="title">as</span> <span class="title">addonsModel</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">think</span>\<span class="title">facade</span>\<span class="title">Log</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 阿里云短信插件</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Aliyunsms</span> <span class="keyword">extends</span> <span class="title">Addons</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">// 该插件的基础信息</span></span><br><span class="line">    <span class="keyword">public</span> $info = [</span><br><span class="line">        <span class="string">'name'</span>        =&gt; <span class="string">'Aliyunsms'</span>,    <span class="comment">// 插件标识</span></span><br><span class="line">        <span class="string">'title'</span>       =&gt; <span class="string">'阿里云短信通道'</span>,    <span class="comment">// 插件名称</span></span><br><span class="line">        <span class="string">'description'</span> =&gt; <span class="string">'阿里云发送短信插件，请勿和其它短信通道一起使用'</span>,    <span class="comment">// 插件简介</span></span><br><span class="line">        <span class="string">'status'</span>      =&gt; <span class="number">0</span>,    <span class="comment">// 状态</span></span><br><span class="line">        <span class="string">'author'</span>      =&gt; <span class="string">'mark'</span>,</span><br><span class="line">        <span class="string">'version'</span>     =&gt; <span class="string">'0.2'</span>,</span><br><span class="line">    ];</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 插件安装方法</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> bool</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">install</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 插件卸载方法</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> bool</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">uninstall</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 实现发送短信</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> mixed</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">sendsms</span><span class="params">($data)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $result     = [</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">false</span>,</span><br><span class="line">            <span class="string">'data'</span>   =&gt; [],</span><br><span class="line">            <span class="string">'msg'</span>    =&gt; <span class="string">'发送失败'</span></span><br><span class="line">        ];</span><br><span class="line">        $addonModel = <span class="keyword">new</span> addonsModel();</span><br><span class="line">        $setting    = $addonModel-&gt;getSetting(<span class="keyword">$this</span>-&gt;info[<span class="string">'name'</span>]);</span><br><span class="line">        $params     = <span class="keyword">array</span>();</span><br><span class="line">        <span class="comment">// *** 需用户填写部分 ***</span></span><br><span class="line">        <span class="comment">// fixme 必填：是否启用https</span></span><br><span class="line">        $security = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息</span></span><br><span class="line">        $accessKeyId     = trim($setting[<span class="string">'accessKeyId'</span>]);</span><br><span class="line">        $accessKeySecret = trim($setting[<span class="string">'accessKeySecret'</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($data[<span class="string">'params'</span>][<span class="string">'code'</span>] == <span class="string">'seller_order_notice'</span>) &#123;</span><br><span class="line">            $data[<span class="string">'params'</span>][<span class="string">'mobile'</span>] = trim(getSetting(<span class="string">'shop_mobile'</span>));</span><br><span class="line">            <span class="keyword">if</span> (!$data[<span class="string">'params'</span>][<span class="string">'mobile'</span>]) &#123;</span><br><span class="line">                $result[<span class="string">'msg'</span>] = <span class="string">'商户手机号不存在'</span>;</span><br><span class="line">                <span class="keyword">return</span> $result;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// fixme 必填: 短信接收号码</span></span><br><span class="line">        $params[<span class="string">"PhoneNumbers"</span>] = trim($data[<span class="string">'params'</span>][<span class="string">'mobile'</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign</span></span><br><span class="line">        $params[<span class="string">"SignName"</span>] = trim($setting[<span class="string">'aliyunPrefix'</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template</span></span><br><span class="line">        <span class="keyword">if</span> (!<span class="keyword">isset</span>($setting[$data[<span class="string">'params'</span>][<span class="string">'code'</span>]][<span class="string">'data'</span>][<span class="string">'title'</span>][<span class="string">'value'</span>])) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'请先配置后台短信接口'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        $params[<span class="string">"TemplateCode"</span>] = trim($setting[$data[<span class="string">'params'</span>][<span class="string">'code'</span>]][<span class="string">'data'</span>][<span class="string">'title'</span>][<span class="string">'value'</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项</span></span><br><span class="line">        $params[<span class="string">'TemplateParam'</span>] = <span class="keyword">$this</span>-&gt;getTemplateData($data[<span class="string">'params'</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// *** 需用户填写部分结束, 以下代码若无必要无需更改 ***</span></span><br><span class="line">        <span class="keyword">if</span> (!<span class="keyword">empty</span>($params[<span class="string">"TemplateParam"</span>]) &amp;&amp; is_array($params[<span class="string">"TemplateParam"</span>])) &#123;</span><br><span class="line">            $params[<span class="string">"TemplateParam"</span>] = json_encode($params[<span class="string">"TemplateParam"</span>], JSON_UNESCAPED_UNICODE);</span><br><span class="line">        &#125;</span><br><span class="line">        Log::info(<span class="string">'aliyunsms:'</span> . json_encode($params));</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            $content = <span class="keyword">$this</span>-&gt;request(</span><br><span class="line">                $accessKeyId,</span><br><span class="line">                $accessKeySecret,</span><br><span class="line">                <span class="string">"dysmsapi.aliyuncs.com"</span>,</span><br><span class="line">                array_merge($params, <span class="keyword">array</span>(</span><br><span class="line">                    <span class="string">"RegionId"</span> =&gt; <span class="string">"cn-hangzhou"</span>,</span><br><span class="line">                    <span class="string">"Action"</span>   =&gt; <span class="string">"SendSms"</span>,</span><br><span class="line">                    <span class="string">"Version"</span>  =&gt; <span class="string">"2017-05-25"</span>,</span><br><span class="line">                )),</span><br><span class="line">                $security</span><br><span class="line">            );</span><br><span class="line">            <span class="keyword">if</span> ($content-&gt;Code != <span class="string">'OK'</span>) &#123;</span><br><span class="line">                Log::error($content-&gt;Message);</span><br><span class="line">                $result[<span class="string">'msg'</span>] = $content-&gt;Message;</span><br><span class="line">                <span class="keyword">return</span> $result;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (\<span class="keyword">Exception</span> $e) &#123;</span><br><span class="line">            Log::error($e-&gt;getMessage());</span><br><span class="line">            $result[<span class="string">'msg'</span>] = $e-&gt;getMessage();</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        $result[<span class="string">'status'</span>] = <span class="keyword">true</span>;</span><br><span class="line">        $result[<span class="string">'msg'</span>]    = <span class="string">'发送成功'</span>;</span><br><span class="line">        <span class="keyword">return</span> $result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 短信接口配置</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> array $params</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> mixed</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">config</span><span class="params">($params = [])</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $config = <span class="keyword">$this</span>-&gt;getConfig();</span><br><span class="line">        <span class="keyword">$this</span>-&gt;assign(<span class="string">'config'</span>, $config);</span><br><span class="line">        <span class="keyword">$this</span>-&gt;assign(<span class="string">'config_params'</span>, $params);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;fetch(<span class="string">'config'</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 模板转换</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $params</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> mixed</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">getTemplateData</span><span class="params">($params)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $config   = <span class="keyword">$this</span>-&gt;getConfig();</span><br><span class="line">        $variable = $config[<span class="string">'template'</span>][$params[<span class="string">'code'</span>]][<span class="string">'data'</span>][<span class="string">'template'</span>][<span class="string">'variable'</span>];</span><br><span class="line">        <span class="keyword">foreach</span> ($variable <span class="keyword">as</span> $key =&gt; $val) &#123;</span><br><span class="line">            $variable[$key] = $params[<span class="string">'params'</span>][$val];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> $variable;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 生成签名并发起请求</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $accessKeySecret string AccessKeySecret</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $domain string API接口所在域名</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $params array API具体参数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $security boolean 使用https</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $method boolean 使用GET或POST方法请求，VPC仅支持POST</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> bool|\stdClass 返回API接口调用结果，当发生错误时返回false</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">request</span><span class="params">($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = <span class="string">'POST'</span>)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $apiParams = array_merge(<span class="keyword">array</span>(</span><br><span class="line">            <span class="string">"SignatureMethod"</span>  =&gt; <span class="string">"HMAC-SHA1"</span>,</span><br><span class="line">            <span class="string">"SignatureNonce"</span>   =&gt; uniqid(mt_rand(<span class="number">0</span>, <span class="number">0xffff</span>), <span class="keyword">true</span>),</span><br><span class="line">            <span class="string">"SignatureVersion"</span> =&gt; <span class="string">"1.0"</span>,</span><br><span class="line">            <span class="string">"AccessKeyId"</span>      =&gt; $accessKeyId,</span><br><span class="line">            <span class="string">"Timestamp"</span>        =&gt; gmdate(<span class="string">"Y-m-d\TH:i:s\Z"</span>),</span><br><span class="line">            <span class="string">"Format"</span>           =&gt; <span class="string">"JSON"</span>,</span><br><span class="line">        ), $params);</span><br><span class="line">        ksort($apiParams);</span><br><span class="line"></span><br><span class="line">        $sortedQueryStringTmp = <span class="string">""</span>;</span><br><span class="line">        <span class="keyword">foreach</span> ($apiParams <span class="keyword">as</span> $key =&gt; $value) &#123;</span><br><span class="line">            $sortedQueryStringTmp .= <span class="string">"&amp;"</span> . <span class="keyword">$this</span>-&gt;encode($key) . <span class="string">"="</span> . <span class="keyword">$this</span>-&gt;encode($value);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $stringToSign = <span class="string">"$&#123;method&#125;&amp;%2F&amp;"</span> . <span class="keyword">$this</span>-&gt;encode(substr($sortedQueryStringTmp, <span class="number">1</span>));</span><br><span class="line"></span><br><span class="line">        $sign = base64_encode(hash_hmac(<span class="string">"sha1"</span>, $stringToSign, $accessKeySecret . <span class="string">"&amp;"</span>, <span class="keyword">true</span>));</span><br><span class="line"></span><br><span class="line">        $signature = <span class="keyword">$this</span>-&gt;encode($sign);</span><br><span class="line"></span><br><span class="line">        $url = ($security ? <span class="string">'https'</span> : <span class="string">'http'</span>) . <span class="string">"://&#123;$domain&#125;/"</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            $content = <span class="keyword">$this</span>-&gt;fetchContent($url, $method, <span class="string">"Signature=&#123;$signature&#125;&#123;$sortedQueryStringTmp&#125;"</span>);</span><br><span class="line">            <span class="keyword">return</span> json_decode($content);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (\<span class="keyword">Exception</span> $e) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">encode</span><span class="params">($str)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $res = urlencode($str);</span><br><span class="line">        $res = preg_replace(<span class="string">"/\+/"</span>, <span class="string">"%20"</span>, $res);</span><br><span class="line">        $res = preg_replace(<span class="string">"/\*/"</span>, <span class="string">"%2A"</span>, $res);</span><br><span class="line">        $res = preg_replace(<span class="string">"/%7E/"</span>, <span class="string">"~"</span>, $res);</span><br><span class="line">        <span class="keyword">return</span> $res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">fetchContent</span><span class="params">($url, $method, $body)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $ch = curl_init();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($method == <span class="string">'POST'</span>) &#123;</span><br><span class="line">            curl_setopt($ch, CURLOPT_POST, <span class="number">1</span>);<span class="comment">//post提交方式</span></span><br><span class="line">            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            $url .= <span class="string">'?'</span> . $body;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        curl_setopt($ch, CURLOPT_URL, $url);</span><br><span class="line">        curl_setopt($ch, CURLOPT_TIMEOUT, <span class="number">5</span>);</span><br><span class="line">        curl_setopt($ch, CURLOPT_RETURNTRANSFER, <span class="number">1</span>);</span><br><span class="line">        curl_setopt($ch, CURLOPT_HTTPHEADER, <span class="keyword">array</span>(</span><br><span class="line">            <span class="string">"x-sdk-client"</span> =&gt; <span class="string">"php/2.0.0"</span>,</span><br><span class="line">        ));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (substr($url, <span class="number">0</span>, <span class="number">5</span>) == <span class="string">'https'</span>) &#123;</span><br><span class="line">            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, <span class="keyword">false</span>);</span><br><span class="line">            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, <span class="keyword">false</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $rtn = curl_exec($ch);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($rtn === <span class="keyword">false</span>) &#123;</span><br><span class="line">            <span class="comment">// 大多由设置等原因引起，一般无法保障后续逻辑正常执行，</span></span><br><span class="line">            <span class="comment">// 所以这里触发的是E_USER_ERROR，会终止脚本执行，无法被try...catch捕获，需要用户排查环境、网络等故障</span></span><br><span class="line">            trigger_error(<span class="string">"[CURL_"</span> . curl_errno($ch) . <span class="string">"]: "</span> . curl_error($ch), E_USER_ERROR);</span><br><span class="line">        &#125;</span><br><span class="line">        curl_close($ch);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $rtn;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="调用插件方法"><a href="#调用插件方法" class="headerlink" title="调用插件方法"></a>调用插件方法</h4><p>安装插件</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">Manage</span>\<span class="title">controller</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">controller</span>\<span class="title">Manage</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Request</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">Addons</span> <span class="title">as</span> <span class="title">addonsModel</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">Hooks</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">think</span>\<span class="title">facade</span>\<span class="title">Cache</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Addons</span> <span class="keyword">extends</span> <span class="title">Manage</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 安装插件</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">install</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $result     = [</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">false</span>,</span><br><span class="line">            <span class="string">'msg'</span>    =&gt; <span class="string">'安装失败'</span>,</span><br><span class="line">            <span class="string">'data'</span>   =&gt; <span class="string">''</span>,</span><br><span class="line">        ];</span><br><span class="line">        $addon_name = input(<span class="string">'name/s'</span>, <span class="string">''</span>);</span><br><span class="line">        <span class="keyword">if</span> (!$addon_name) &#123;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        $class = get_addon_class($addon_name);</span><br><span class="line">        <span class="keyword">if</span> (!class_exists($class)) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'插件不存在'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $addons = <span class="keyword">new</span> $class;</span><br><span class="line">        $info   = $addons-&gt;info;</span><br><span class="line">        <span class="keyword">if</span> (!$info) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'插件信息缺失'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 调用插件的install方法</span></span><br><span class="line">        $install_flag = $addons-&gt;install();</span><br><span class="line">        <span class="keyword">if</span> (!$install_flag) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'执行插件预安装失败'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 更新hook表、addons表</span></span><br><span class="line">        $addonsModel = <span class="keyword">new</span> addonsModel();</span><br><span class="line">        $res         = $addonsModel-&gt;add($info);</span><br><span class="line">        $res         = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">if</span> (!$res) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'插件数据库安装失败'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            $hookModel = <span class="keyword">new</span> Hooks();</span><br><span class="line">            $config    = [</span><br><span class="line">                <span class="string">'config'</span> =&gt; json_encode($addons-&gt;getConfig())</span><br><span class="line">            ];</span><br><span class="line">            $addonsModel-&gt;save($config, [<span class="string">'name'</span> =&gt; $addon_name]);<span class="comment">//更新配置</span></span><br><span class="line"></span><br><span class="line">            $hooks_update = $hookModel-&gt;updateHooks($addon_name);<span class="comment">//更新钩子</span></span><br><span class="line">            <span class="keyword">if</span> ($hooks_update) &#123;</span><br><span class="line">                Cache::set(<span class="string">'hooks'</span>, <span class="keyword">null</span>);</span><br><span class="line">                $result[<span class="string">'msg'</span>]    = <span class="string">'安装成功'</span>;</span><br><span class="line">                $result[<span class="string">'status'</span>] = <span class="keyword">true</span>;</span><br><span class="line">                <span class="keyword">return</span> $result;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                $addonsModel-&gt;where([<span class="string">'name'</span> =&gt; $addon_name])-&gt;delete();</span><br><span class="line">                $result[<span class="string">'msg'</span>]    = <span class="string">'安装失败，请重试'</span>;</span><br><span class="line">                $result[<span class="string">'status'</span>] = <span class="keyword">true</span>;</span><br><span class="line">                <span class="keyword">return</span> $result;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>卸载插件：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">Manage</span>\<span class="title">controller</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">controller</span>\<span class="title">Manage</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Request</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">Addons</span> <span class="title">as</span> <span class="title">addonsModel</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">Hooks</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">think</span>\<span class="title">facade</span>\<span class="title">Cache</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Addons</span> <span class="keyword">extends</span> <span class="title">Manage</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 卸载插件</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">uninstall</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $result      = [</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">false</span>,</span><br><span class="line">            <span class="string">'msg'</span>    =&gt; <span class="string">'卸载失败'</span>,</span><br><span class="line">            <span class="string">'data'</span>   =&gt; <span class="string">''</span>,</span><br><span class="line">        ];</span><br><span class="line">        $addonsModel = <span class="keyword">new</span> addonsModel();</span><br><span class="line">        $addon_name  = input(<span class="string">'name'</span>, <span class="string">''</span>);</span><br><span class="line">        $addons      = $addonsModel-&gt;where([<span class="string">'name'</span> =&gt; $addon_name])-&gt;find();</span><br><span class="line">        <span class="keyword">if</span> (!$addons) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'插件不存在'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        $addons = $addons-&gt;toArray();</span><br><span class="line">        $class  = get_addon_class($addons[<span class="string">'name'</span>]);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!$addons || !class_exists($class)) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'插件不存在'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        $addon_class    = <span class="keyword">new</span> $class;</span><br><span class="line">        <span class="comment">// 调用插件类的uninstall方法</span></span><br><span class="line">        $uninstall_flag = $addon_class-&gt;uninstall();</span><br><span class="line">        <span class="keyword">if</span> (!$uninstall_flag) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'插件预卸载失败'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        $hookModel    = <span class="keyword">new</span> Hooks();</span><br><span class="line">        <span class="comment">// 更新hooks表的addons插件字段，删除字段中的插件：$addons['name']</span></span><br><span class="line">        $hooks_update = $hookModel-&gt;removeHooks($addons[<span class="string">'name'</span>]);</span><br><span class="line">        <span class="keyword">if</span> ($hooks_update === <span class="keyword">false</span>) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'插件预卸载失败'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">        Cache::set(<span class="string">'hooks'</span>, <span class="keyword">null</span>);</span><br><span class="line">        $delete = $addonsModel-&gt;where([<span class="string">'name'</span> =&gt; $addons[<span class="string">'name'</span>]])-&gt;delete();</span><br><span class="line">        <span class="keyword">if</span> ($delete === <span class="keyword">false</span>) &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">'卸载插件失败'</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>]    = <span class="string">'卸载成功'</span>;</span><br><span class="line">            $result[<span class="string">'status'</span>] = <span class="keyword">true</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">		.</span><br><span class="line">		.</span><br><span class="line">		.</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>发送短信<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sms</span> <span class="keyword">extends</span> <span class="title">Common</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">   <span class="comment">/***</span></span><br><span class="line"><span class="comment">     * 发送短信</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $mobile</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $content</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $code</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $params</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> array</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">send_sms</span><span class="params">($mobile, $content, $code, $params)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $result = [</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">true</span>,</span><br><span class="line">            <span class="string">'data'</span> =&gt; <span class="string">''</span>,</span><br><span class="line">            <span class="string">'msg'</span> =&gt; <span class="string">'发送成功'</span></span><br><span class="line">        ];</span><br><span class="line">        <span class="comment">// 依次执行sendsms标签绑定的发短信插件类的sendsms方法</span></span><br><span class="line">        $re = hook(<span class="string">'sendsms'</span>, [<span class="string">'params'</span> =&gt; [</span><br><span class="line">            <span class="string">'mobile'</span>  =&gt; $mobile,</span><br><span class="line">            <span class="string">'content'</span> =&gt; $content,</span><br><span class="line">            <span class="string">'code'</span>    =&gt; $code,</span><br><span class="line">            <span class="string">'params'</span>  =&gt; $params,</span><br><span class="line">        ]]);</span><br><span class="line">        <span class="keyword">if</span>($re &amp;&amp; is_array($re))&#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">isset</span>($re[<span class="number">0</span>][<span class="string">'status'</span>]) &amp;&amp; $re[<span class="number">0</span>][<span class="string">'status'</span>]) &#123;</span><br><span class="line"><span class="comment">//                $result['status'] = true;</span></span><br><span class="line"><span class="comment">//                $result['msg'] = '发送成功';</span></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                $result[<span class="string">'status'</span>] = <span class="keyword">false</span>;</span><br><span class="line">                $result[<span class="string">'msg'</span>] = <span class="keyword">isset</span>($re[<span class="number">0</span>][<span class="string">'msg'</span>]) ? $re[<span class="number">0</span>][<span class="string">'msg'</span>] : <span class="string">'发送失败'</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> $result;</span><br><span class="line">    &#125;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>其中hook函数为自定义的，调用了\think\Hook::listen()，代码如下：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hook</span><span class="params">($hook, $params = [])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    $result = Hook::listen($hook, $params);</span><br><span class="line">    <span class="keyword">if</span> (count($result) &gt; <span class="number">0</span> &amp;&amp; $result[<span class="number">0</span>]) &#123;</span><br><span class="line">        <span class="keyword">return</span> $result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="接口路由"><a href="#接口路由" class="headerlink" title="接口路由"></a>接口路由</h3><p>看一下 Api 基类,所有的api接口都必须执行  Index 控制器的 index 方法</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">controller</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Api</span> <span class="keyword">extends</span> <span class="title">Base</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">protected</span> $userId = <span class="number">0</span>;                        <span class="comment">//用户id</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">protected</span> <span class="function"><span class="keyword">function</span> <span class="title">initialize</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        error_reporting(E_ERROR | E_WARNING | E_PARSE);</span><br><span class="line">        <span class="keyword">parent</span>::initialize();</span><br><span class="line">        <span class="comment">//配置统一入口，只让访问init方法</span></span><br><span class="line">        <span class="keyword">if</span>(request()-&gt;module()!= <span class="string">'api'</span> || request()-&gt;controller() != <span class="string">'Index'</span> || request()-&gt;action() != <span class="string">'index'</span>)&#123;</span><br><span class="line">            <span class="keyword">die</span>(<span class="string">'error'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//此方法用于设置参数</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">setInit</span><span class="params">($user_id)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">$this</span>-&gt;userId = $user_id;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Index控制器的index方法，要求传递method参数，method参数格式为“控制器.方法“，如：user.getarealist，则表示调用user控制器的getarealist方法。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">api</span>\<span class="title">controller</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">controller</span>\<span class="title">Api</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>\<span class="title">UserToken</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Index</span> <span class="keyword">extends</span> <span class="title">Api</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">protected</span> $loginAction = [];</span><br><span class="line">    <span class="keyword">protected</span> $action = [];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">index</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">//解决跨域问题</span></span><br><span class="line"><span class="comment">/*      header('Access-Control-Allow-Origin:*');//允许所有来源访问</span></span><br><span class="line"><span class="comment">        header('Access-Control-Allow-Method:POST,GET');//允许访问的方式*/</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>($_SERVER[<span class="string">'REQUEST_METHOD'</span>] == <span class="string">'OPTIONS'</span>)&#123;</span><br><span class="line">            header(<span class="string">"Access-Control-Allow-Origin: *"</span>);</span><br><span class="line">            header(<span class="string">"Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"</span>);</span><br><span class="line">            header(<span class="string">'Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'</span>);</span><br><span class="line">            <span class="keyword">exit</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        header(<span class="string">"Access-Control-Allow-Origin:*"</span>);</span><br><span class="line">        header(<span class="string">"Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"</span>);</span><br><span class="line">        header(<span class="string">'Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'</span>);</span><br><span class="line"></span><br><span class="line">        $result = [</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">false</span>,</span><br><span class="line">            <span class="string">'data'</span> =&gt; [],</span><br><span class="line">            <span class="string">'msg'</span> =&gt; <span class="string">''</span></span><br><span class="line">        ];</span><br><span class="line">        $api = config(<span class="string">'api.'</span>);</span><br><span class="line">        $method = explode(<span class="string">'.'</span>,input(<span class="string">'param.method'</span>));</span><br><span class="line">        <span class="keyword">if</span>(count($method) != <span class="number">2</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> error_code(<span class="number">14002</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">isset</span>($api[$method[<span class="number">0</span>]]))&#123;</span><br><span class="line">            $cname = $api[$method[<span class="number">0</span>]][<span class="string">'code'</span>];   <span class="comment">// 类名</span></span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> error_code(<span class="number">14003</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">isset</span>($api[$method[<span class="number">0</span>]][<span class="string">'method'</span>][$method[<span class="number">1</span>]]))&#123;   <span class="comment">// 是否存在方法</span></span><br><span class="line">            $aname = $api[$method[<span class="number">0</span>]][<span class="string">'method'</span>][$method[<span class="number">1</span>]][<span class="string">'code'</span>];</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> error_code(<span class="number">14004</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//判断是否需要登陆</span></span><br><span class="line">        <span class="keyword">if</span>($api[$method[<span class="number">0</span>]][<span class="string">'method'</span>][$method[<span class="number">1</span>]][<span class="string">'is_login'</span>])&#123;</span><br><span class="line">            <span class="keyword">if</span>(!input(<span class="string">'?param.token'</span>))&#123;</span><br><span class="line">                <span class="keyword">return</span> error_code(<span class="number">14006</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            $userTokenModel = <span class="keyword">new</span> UserToken();</span><br><span class="line">            $result = $userTokenModel-&gt;checkToken(input(<span class="string">'param.token'</span>));</span><br><span class="line">            <span class="keyword">if</span>(!$result[<span class="string">'status'</span>])&#123;</span><br><span class="line">                <span class="keyword">return</span> error_code(<span class="number">14007</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="keyword">$this</span>-&gt;userId = $result[<span class="string">'data'</span>][<span class="string">'user_id'</span>];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">$this</span>-&gt;userId = <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            $c = controller($cname);   <span class="comment">// 实例化控制器</span></span><br><span class="line">            $c-&gt;setInit(<span class="keyword">$this</span>-&gt;userId);   <span class="comment">// $c-&gt;userId = $this-&gt;userId;（多余的）</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (\<span class="keyword">Exception</span> $e) &#123;</span><br><span class="line">            <span class="keyword">return</span> error_code(<span class="number">14008</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(!method_exists($c, $aname))&#123;</span><br><span class="line">            <span class="keyword">return</span> error_code(<span class="number">14009</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        trace(input(<span class="string">'param.'</span>),<span class="string">'api'</span>);</span><br><span class="line">        $data = $c-&gt;$aname();   <span class="comment">// 调用控制器的方法</span></span><br><span class="line">        trace($data,<span class="string">'api'</span>);</span><br><span class="line">        <span class="keyword">return</span> $data;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>其中用到的 UserToken 类：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">common</span>\<span class="title">model</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserToken</span> <span class="keyword">extends</span> <span class="title">Common</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 登陆存token</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $user_id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> int $platform     //1就是h5登陆（h5端和微信公众号端），2就是微信小程序登陆，3是支付宝小程序，4是app，5是pc</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> array</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">setToken</span><span class="params">($user_id,$platform=<span class="number">1</span>)</span></span>&#123;</span><br><span class="line">        $result = <span class="keyword">array</span>(</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">false</span>,</span><br><span class="line">            <span class="string">'data'</span> =&gt; <span class="string">''</span>,</span><br><span class="line">            <span class="string">'msg'</span> =&gt; <span class="string">''</span></span><br><span class="line">        );</span><br><span class="line">        $userModel = <span class="keyword">new</span> User();</span><br><span class="line">        $userInfo = $userModel-&gt;where(<span class="keyword">array</span>(<span class="string">'id'</span>=&gt;$user_id))-&gt;find();</span><br><span class="line">        <span class="keyword">if</span>($userInfo)&#123;</span><br><span class="line">            $data[<span class="string">'user_id'</span>] = $user_id;</span><br><span class="line">            $data[<span class="string">'platform'</span>] = $platform;</span><br><span class="line">            $data[<span class="string">'ctime'</span>] = time();</span><br><span class="line">            $data[<span class="string">'token'</span>] = <span class="keyword">$this</span>-&gt;algorithm($userInfo[<span class="string">'id'</span>],$userInfo[<span class="string">'password'</span>],$platform,$data[<span class="string">'ctime'</span>]);</span><br><span class="line">            $re = <span class="keyword">$this</span>-&gt;save($data);</span><br><span class="line">            <span class="keyword">if</span>($re &gt;<span class="number">0</span>)&#123;</span><br><span class="line">                <span class="comment">//删除掉旧的token</span></span><br><span class="line">                $where[] = [<span class="string">'user_id'</span>, <span class="string">'eq'</span>, $user_id];</span><br><span class="line">                $where[] = [<span class="string">'platform'</span>, <span class="string">'eq'</span>, $platform];</span><br><span class="line">                $where[] = [<span class="string">'token'</span>, <span class="string">'neq'</span>, $data[<span class="string">'token'</span>]];</span><br><span class="line">                <span class="keyword">$this</span>-&gt;where($where)-&gt;delete();</span><br><span class="line"></span><br><span class="line">                $result[<span class="string">'data'</span>] = $data[<span class="string">'token'</span>];</span><br><span class="line">                $result[<span class="string">'status'</span>] = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> $result;</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                $result[<span class="string">'msg'</span>] = <span class="string">"生成token失败"</span>;</span><br><span class="line">                <span class="keyword">return</span> $result;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(!$userInfo)&#123;</span><br><span class="line">                $result[<span class="string">'msg'</span>] = <span class="string">"用户不存在"</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">delToken</span><span class="params">($token)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $result = <span class="keyword">array</span>(</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">false</span>,</span><br><span class="line">            <span class="string">'data'</span> =&gt; <span class="string">''</span>,</span><br><span class="line">            <span class="string">'msg'</span> =&gt; <span class="string">''</span></span><br><span class="line">        );</span><br><span class="line">        <span class="comment">//删除掉旧的token</span></span><br><span class="line">        <span class="comment">//$where[] = ['user_id', 'eq', $user_id];</span></span><br><span class="line">        $where[] = [<span class="string">'token'</span>, <span class="string">'eq'</span>, $token];</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;where($where)-&gt;delete())&#123;</span><br><span class="line">            $result[<span class="string">'status'</span>] = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> $result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据token来获取用户的id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> $token //token的值</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> int $status //用户状态，0是所有状态，1是取正常的用户状态</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> array|mixed</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> \think\db\exception\DataNotFoundException</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> \think\db\exception\ModelNotFoundException</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> \think\exception\DbException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">checkToken</span><span class="params">($token, $status = <span class="number">1</span>)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $result = [</span><br><span class="line">            <span class="string">'status'</span> =&gt; <span class="keyword">false</span>,</span><br><span class="line">            <span class="string">'data'</span> =&gt; <span class="string">''</span>,</span><br><span class="line">            <span class="string">'msg'</span> =&gt; <span class="string">''</span></span><br><span class="line">        ];</span><br><span class="line">        <span class="keyword">if</span>(!$token)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">return</span> error_code(<span class="number">14006</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $where[] = [<span class="string">'token'</span>, <span class="string">'eq'</span>, $token];</span><br><span class="line">        $tokenInfo = <span class="keyword">$this</span>-&gt;where($where)-&gt;cache(<span class="keyword">true</span>)-&gt;find();</span><br><span class="line">        <span class="keyword">if</span>($tokenInfo)&#123;</span><br><span class="line">            <span class="comment">//密码有效期半年</span></span><br><span class="line">            <span class="keyword">if</span>($tokenInfo[<span class="string">'ctime'</span>] &lt; time() - <span class="number">60</span>*<span class="number">60</span>*<span class="number">24</span>*<span class="number">180</span>)&#123;</span><br><span class="line">                <span class="keyword">return</span> error_code(<span class="number">11026</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            $userModel = <span class="keyword">new</span> User();</span><br><span class="line">            $where1[] = [<span class="string">'id'</span>,<span class="string">'eq'</span>, $tokenInfo[<span class="string">'user_id'</span>]];</span><br><span class="line">            $userInfo = $userModel-&gt;where($where1)-&gt;find();</span><br><span class="line">            <span class="keyword">if</span>(!$userInfo)&#123; <span class="comment">// 用户不存在</span></span><br><span class="line">                <span class="keyword">return</span> error_code(<span class="number">11004</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>($status == <span class="number">1</span> &amp;&amp; $userInfo[<span class="string">'status'</span>] != <span class="number">1</span>)&#123;</span><br><span class="line">                <span class="keyword">return</span> error_code(<span class="number">11022</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            $result[<span class="string">'status'</span>] = <span class="keyword">true</span>;</span><br><span class="line">            $result[<span class="string">'data'</span>] = $tokenInfo;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            $result[<span class="string">'msg'</span>] = <span class="string">"不是有效的token"</span>;</span><br><span class="line">            <span class="keyword">return</span> $result;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 登录返回token的生成方式</span></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">algorithm</span><span class="params">($user_id,$password,$platform,$createtime)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> md5(md5($user_id.$password.$platform.$createtime).rand(<span class="number">1</span>,<span class="number">10000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/d2691605.html" title="jshop thinkphp开源电商系统笔记">http://blog.yunshu168.com/posts/d2691605.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/223511c.html" rel="next" title="ThinkPHP 5 钩子相关源码解析">
                <i class="fa fa-chevron-left"></i> ThinkPHP 5 钩子相关源码解析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/4e47881d.html" rel="prev" title="ThinkPHP5.1x 中间件实现原理">
                ThinkPHP5.1x 中间件实现原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用插件扩展功能"><span class="nav-number">1.</span> <span class="nav-text">使用插件扩展功能</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#appInit-标签中绑定InitHooks插件"><span class="nav-number">1.1.</span> <span class="nav-text">appInit 标签中绑定InitHooks插件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#定义应用功能插件"><span class="nav-number">1.2.</span> <span class="nav-text">定义应用功能插件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#调用插件方法"><span class="nav-number">1.3.</span> <span class="nav-text">调用插件方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#接口路由"><span class="nav-number">2.</span> <span class="nav-text">接口路由</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
